$(document).ready(function(){
   $('#checkAccountDetails').on('click',function(){
      if($(this).hasClass('open')) {
         $(this).removeClass('open').find('i.icon_down').removeClass('icon_up');
         $('#accountDetails').hide();
      } else {
         $(this).addClass('open').find('i.icon_down').addClass('icon_up');
         $('#accountDetails').show();
      }
      return false;
   });
   
   var createOrder = function(target, data, callback){
      $.ajax({
         type: 'POST',
         url: OC.filePath('company', 'ajax', 'createorder.php'),
         data: data,
         beforeSend: function(xhr, settings) {
            if(!showLoading(target, settings, null, {button:true}))
               return false;
         },
         success: function(result){
            if (!isLoggedIn(result, target)) {
               window.location = redirect_url;
               return;
            }
            
            if(!$.isPlainObject(result)) {
               result = $.parseJSON(result);
            }
            
            if(result.status === 'success') {
               if($.isFunction(callback)) {
                  callback();
               }
               $('#showOrderList').find('.orderCount').text(result.data.order_count);
               $.ajax({
                  type: 'GET',
                  url: OC.filePath('company', 'ajax', 'getorder.php'),
                  data: {order_id: result.data.order_id},
                  cache: false,
                  beforeSend: function() {
                     $('#orderDetailBody').html('').css('minHeight', 200);
                     $('#orderDetail').modal('show').show();
                     if(!showLoading($('#orderDetail'), null, null, {opacity : '1'}))
                        return false;
                  },
                  success: function(result) {
                     $('#orderDetailBody').css('minHeight', 0).html(result);
                  }
               });
            } else {
               showMessagePanel(result.data.message, target, true, {placement:'bottom'});
            }
         }
      });
   }
   
   $('#accountLevel').on('click', '.upgrade', function(){
      var data = {};
      var target = $(this);
      data.order_type = 'upgrade';
      data.upgrade_type = target.data('upgrade_type');
      
      var msg = '订单内容：' + target.data('type_name') + '。您确定购买吗？';
      
      showConfirmDialog(msg, function(){
         createOrder(target, data);
      }, null, '订单确认');
      return false;
   });
   
   $('#smsInfo').on('click', '#smsBuy', function(){
      var data = {};
      var target = $(this);
      data.order_type = 'sms';
      data.sms_buy_num = $('#smsBuyNum').val();
      
      var msg = '订单内容：短信包' + data.sms_buy_num + '条，价格：' + (data.sms_buy_num*$(this).data('sms_unit_price')).toFixed(2) + '元。您确定购买吗？';
      
      showConfirmDialog(msg, function(){
         createOrder(target, data);
      }, null, '订单确认');
      return false;
   });
   
   $('#showOrderList').on('click',function(){
      $.ajax({
         type: 'GET',
         url: OC.filePath('company', 'ajax', 'getorderlist.php'),
         cache: false,
         beforeSend: function() {
            $('#orderListBody').html('').css('minHeight', 200);
            $('#orderList').modal('show').show();
            if(!showLoading($('#orderList'), null, null, {opacity : '1'}))
               return false;
         },
         success: function(result) {
            $('#orderListBody').css('minHeight', 0).html(result);
         }
      });
      return false;
   });
   
   if(!(window.XMLHttpRequestUpload && window.FileReader)) {
      $('#uploadReceiptForm .large').html($('#uploadReceiptForm .large').data('nodragtext'));
   }
   
   if($('#uploadReceiptForm').length>0) {
      $('#uploadReceiptForm').fileUploadUIX({
         allowImageType: true, 
         keepList: true,
         autoUpload: true, 
         maxFileSize: 4*1024*1024,
         onError:function(response){
           $("#uploadTable tr:last").remove();
           $("#receipt_upload_error").html(response).fadeOut(3000,function(){
              $(this).html('').fadeIn();
           });
         },
         onCompleteAll: function(list) {
            var order_id = $('#uploadOrderId').val();
            var tr = $('#order_' + order_id);
            
            $('#uploadTable').find('tr.file_upload_error.keeprow').fadeOut(3000, function(){
               $(this).remove();
            });
            
            $.ajax({
               type: 'GET',
               url: OC.filePath('company', 'ajax', 'getreceiptpic.php'),
               data: {order_id: order_id},
               cache: false,
               beforeSend: function() {
                  $('#receiptPicTd').html('');
                  $('#receiptPicTable').show();
                  if(!showLoading($('#receiptPicTd'), null, null, {opacity : '1'}))
                     return false;
               },
               success: function(result) {
                  if(result)
                     $('#receiptPicTable').show();
                  else
                     $('#receiptPicTable').hide();
                  $('#receiptPicTd').html(result);
                  if($('a.uploadReceipt i', tr).length <= 0)
                     $('a.uploadReceipt', tr).append('<i></i>');
               }
            });
         }
      });
   }
   
   $('#orderList').on('click', '.uploadReceipt', function(){
      var target = $(this);
      var td = $(this).closest('td');
      var order_id = td.data('order_id');
      
      $.ajax({
         type: 'GET',
         url: OC.filePath('company', 'ajax', 'getreceiptpic.php'),
         data: {order_id: order_id},
         cache: false,
         beforeSend: function() {
            $('#receiptPicTd').html('');
            $('#uploadOrderId').val(order_id);
            $('#uploadTable').find('tr.file_upload_error').remove();
            $('#uploadReceiptDiv').show().position({
               my: 'right top',
               at: 'left+95 bottom+10',
               of: target,
               collision: 'none'
            });
            
            $('#receiptPicTable').show();
            if(!showLoading($('#receiptPicTd'), null, null, {opacity : '1'}))
               return false;
         },
         success: function(result) {
            if(result)
               $('#receiptPicTable').show();
            else
               $('#receiptPicTable').hide();
            $('#receiptPicTd').html(result);
         }
      });
      
      return false;
   }).on('click', '#uploadReceiptDiv .closediv', function(){
      $('#uploadReceiptDiv').hide();
      return false;
   }).on('click', '.cancelOrder', function(){
      var target = $(this);
      var td = $(this).closest('td');
      var order_id = td.data('order_id');
      
      $('#orderList').hide().modal('hide');
      
      showConfirmDialog('确认取消该订单么？',function() {
         $.ajax({
            type: 'POST',
            url: OC.filePath('company', 'ajax', 'setorderstatus.php'),
            data: {order_id: order_id, action: 'cancel_order'},
            beforeSend: function(xhr, settings) {
               if(!showLoading(target, settings, null, {button:true}))
                  return false;
            },
            success: function(result){
               if (!isLoggedIn(result, target)) {
                  window.location = redirect_url;
                  return;
               }
               
               if(!$.isPlainObject(result)) {
                  result = $.parseJSON(result);
               }
               
               $('#orderList').modal('show');
               
               if(result.status === 'success') {
                  $('#uploadReceiptDiv').hide();
                  td.text('已取消');
               } else {
                  showMessagePanel(result.data.message, target, true, {placement:'right'});
               }
            }
         });
      }, function() {
         $('#orderList').modal('show');
      });
      
      return false;
   }).on('click', '#pager li.active', function(){
      $('#uploadReceiptDiv').hide();
   }).on('hidden', function(){
      $('#uploadReceiptDiv').hide();
   });
   
   $('#orderDetail').on('click', '.orderManage', function(){
      $('#orderDetail').one('hidden', function(){
         $('#showOrderList').trigger('click');
      }).modal('hide');
      return false;
   });
   
   $('#emailSmsSettingForm').on('click', '.send_surebtn', function(){
      var target = $(this);
      $('#emailSmsSettingForm').ajaxSubmit({
         dataType: 'json',
         beforeSubmit: function(data, form, options) {
            $('.server', form).hide();
            if (!showLoading(target, options, null, {button:true}))
               return false;
         },
         success: function(result, status, xhr, form) {
            if (result.status != 'success') {
               $('.server', form).jobUtil('showError', result.data.message);
            } else {
               $('.server', form).jobUtil('showSuccess', result.data.message, function(){
                  $('.server', form).fadeOut(3000);
               });
            }
         }
      });
      return false;
   });
   
   $('#smsHistoryBtn').on('click',function(){
      $.ajax({
         type: 'GET',
         url: OC.filePath('company', 'ajax', 'getsmshistory.php'),
         cache: false,
         beforeSend: function() {
            $('#smsHistoryBody').html('').css('minHeight', 200);
            $('#smsHistory').modal('show').show();
            if(!showLoading($('#smsHistory'), null, null, {opacity : '1'}))
               return false;
         },
         success: function(result) {
            $('#smsHistoryBody').css('minHeight', 0).html(result);
         }
      });
      return false;
   });
   
});
